<template>
  <div class="upload-container">
    <!-- 上传按钮集成在输入框中 -->
    <el-input
      v-model="inputValue"
      :disabled="inputDisabled"
      placeholder="请输入内容或上传文件"
      @input="inputValueChange"
      class="upload-input"
    >
      <template #append>
        <!-- 主要上传按钮 -->
        <el-button
          type="primary"
          :disabled="isProcessing || isSelecting"
          @click="handleUploadClick"
        >
          <el-icon v-if="!isProcessing && !isSelecting"><Upload /></el-icon>
          <el-icon v-if="isProcessing || isSelecting"><Loading /></el-icon>
          {{
            isProcessing
              ? "处理中..."
              : isSelecting
              ? "选择文件中..."
              : "选择文件"
          }}
        </el-button>
      </template>
    </el-input>

    <!-- 隐藏的文件输入框 -->
    <input
      ref="fileInput"
      type="file"
      :accept="acceptTypes"
      class="hidden-file-input"
      @change="handleFileSelected"
      @cancel="handleFileSelectionCancel"
    />

    <!-- 进度条，文件选择过程中即显示 -->
    <el-progress
      v-if="isProcessing || isSelecting"
      v-loading.fullscreen.lock="isSelecting"
      :percentage="isSelecting ? 1 : processPercentage"
      :stroke-width="4"
      class="process-bar"
    ></el-progress>

    <!-- 处理状态提示 -->
    <el-alert
      v-if="processMessage"
      :message="processMessage"
      :type="processSuccess ? 'success' : 'info'"
      closable
      class="process-message"
      @close="processMessage = ''"
    ></el-alert>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import axios from "axios";
import { Upload, Loading } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { gmtScriptDebugInfoFile } from "@/api/gmtScript";

// Props 定义
interface Props {
  taskId: any;
  paramValue: any;
}

const props = withDefaults(defineProps<Props>(), {
  taskId: "",
  paramValue: "",
});

// Emits 定义
const emit = defineEmits<{
  (e: "update:paramValue", value: any): void;
}>();

// 输入框绑定值
const inputValue = ref(props.paramValue);
//输入框不可输入
const inputDisabled = ref(true);
// 文件输入框引用
const fileInput = ref(null);
// 处理状态标记（文件解析/上传阶段）
const isProcessing = ref(false);
// 选择状态标记（文件对话框打开阶段）
const isSelecting = ref(false);
// 处理进度百分比
const processPercentage = ref(0);
// 处理状态消息
const processMessage = ref("");
// 处理是否成功
const processSuccess = ref(false);
// 支持的文件类型
const acceptTypes = ".txt,.csv,.xlsx,.xls,.json,.docx,.pdf";

// 监听页面焦点，判断文件选择对话框是否关闭
onMounted(() => {
  document.addEventListener("focus", handleDocumentFocus);
});

// 处理文档焦点事件，判断文件选择框是否关闭
const handleDocumentFocus = () => {
  if (isSelecting.value && !isProcessing.value) {
    // 如果没有选择任何文件
    if (!fileInput.value?.files?.length) {
      handleFileSelectionCancel();
    }
  }
};

// 点击上传按钮时立即触发加载状态
const handleUploadClick = () => {
  if (!isProcessing.value && !isSelecting.value && fileInput.value) {
    // 立即显示选择中状态
    isSelecting.value = true;
    processMessage.value = "请选择要上传的文件...";

    // 重置文件输入
    fileInput.value.value = "";

    // 触发文件选择对话框
    setTimeout(() => {
      fileInput.value.click();
    }, 100);
  }
};

const inputValueChange = () => {
  console.log("11111111");

  emit("update:paramValue", inputValue.value);
};

// 文件选择确认后处理
const handleFileSelected = async (e) => {
  const file = e.target.files[0];
  if (!file) {
    handleFileSelectionCancel();
    return;
  }

  // 从选择状态切换到处理状态
  isSelecting.value = false;
  isProcessing.value = true;
  processPercentage.value = 0;
  processMessage.value = `正在解析文件: ${file.name}`;
  processSuccess.value = false;
  console.log("props.taskId", props.taskId);

  try {
    // 执行文件解析处理
    const processedFile: any = await parseFile(file);
    const formData = new FormData();
    // 解析完成后的处理
    processSuccess.value = true;
    processMessage.value = `文件解析完成: ${
      processedFile.name
    } (${formatFileSize(processedFile.size)})`;

    // 这里可以添加实际的文件处理逻辑
    inputValue.value = `${processedFile.name}`;
    emit("update:paramValue", processedFile.name);
    console.log("processedFile", processedFile, file);

    // 可以在这里添加后续的上传到后端的逻辑
    // await gmtScriptDebugInfoFile({
    //   file:file,
    //   taskId:props.taskId,
    //   fileName:inputValue.value,
    // });
    formData.append("file", file);
    formData.append("scriptId	", props.taskId);
    formData.append("fileName", inputValue.value);
    const res = await axios({
      url: "http://10.222.125.103:18085/gmtScript/info/save/file",
      method: "post",
      headers: {
        "Content-Type": "multipart/form-data",
      },
      data: formData,
      timeout: 1000 * 20,
    }).then((res: any) => {
      console.log("res", res);

      if (res.data.code == 501) {
        ElMessage({
          message: res.data.data,
          type: "warning",
        });
      }
    });

    // 5秒后清除成功消息
    setTimeout(() => {
      processMessage.value = "";
    }, 5000);
  } catch (error) {
    ElMessage.error(`文件处理失败: ${error.message || error}`);
    processMessage.value = `文件处理失败，请重试`;
    processSuccess.value = false;
  } finally {
    // 显示100%状态一小段时间后再隐藏进度条
    setTimeout(() => {
      isProcessing.value = false;
    }, 800);
  }
};

// 取消文件选择
const handleFileSelectionCancel = () => {
  isSelecting.value = false;
  processMessage.value = "";
};

// 模拟文件解析过程
const parseFile = (file) => {
  return new Promise((resolve) => {
    // 根据文件大小调整处理时间
    const fileSize = file.size;
    const totalDuration = Math.min(
      Math.max((fileSize / 1024 / 1024) * 1500, 1000),
      8000
    );
    const interval = 50;
    const steps = totalDuration / interval;
    const increment = 100 / steps;

    let currentProgress = 0;

    const timer = setInterval(() => {
      currentProgress += increment;
      if (currentProgress >= 100) {
        currentProgress = 100;
        clearInterval(timer);
        resolve(file);
      }
      processPercentage.value = Math.floor(currentProgress);
    }, interval);
  });
};

// 格式化文件大小显示
const formatFileSize = (bytes) => {
  if (bytes === 0) return "0 Bytes";
  const k = 1024;
  const sizes = ["Bytes", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};
</script>

<style scoped>
.upload-container {
  width: 260px;
  margin: 0 20px;
}

.process-bar {
  margin-top: 10px;
  width: 100%;
}

.process-message {
  margin-top: 10px;
}

.upload-input {
  width: 100%;
}

.hidden-file-input {
  display: none;
}
</style>
